package com.sakiko.dailynote.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sakiko.dailynote.mapper.ArticleMapper;
import com.sakiko.dailynote.pojo.Article;
import com.sakiko.dailynote.pojo.PageBean;
import com.sakiko.dailynote.service.ArticleService;
import com.sakiko.dailynote.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id =(Integer) map.get("id");
        article.setCreateUser(id);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建 page对象
        PageBean<Article> pageBean = new PageBean<>();

        // 开启 分页查询 pageHelper
        PageHelper.startPage( pageNum, pageSize); // 自动拼接到 mapper

        // 依据接口文档，登录用户只能操作自己发布的文章
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> list = articleMapper.list( userId, categoryId, state);

        // Page中提供了方法，可以获取PageHelper分页查询后的到的总条数和当前页数据
        PageInfo<Article> pageInfo = new PageInfo<>(list);

        // 设置 PageBean 数据
        pageBean.setTotal(pageInfo.getTotal());  // 获取总记录数
        pageBean.setItems(pageInfo.getList());   // 获取当前页数据;

        return pageBean;
    }

    @Override
    public Article getArticle(Integer id) {
        Article article = articleMapper.getArticle(id);
        return article;
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
